package com.tusuo.stds.ui.level;

import android.content.Context;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.LevelResult;
import com.tusuo.stds.util.Utils;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;
import timber.log.Timber;

/**
 * @author J.Huang
 * @version 1.0
 *
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(LevelResultPresenter.class)
class LevelResultPresenter extends MvpBasePresenter<LevelResultView> {

    @Inject
    ApiHelper mApiHelper;

    private Context mContext;
    private String mErrMsgServer;

    private Subscriber<LevelResult> mGetLevelResultSubscriber = null;

    private int mLevelRecordId;

    LevelResultPresenter(Context context, int levelRecordId) {
        mContext = context;
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);
        mLevelRecordId = levelRecordId;

        Injector.initLevelResultPresenterComponent().inject(this);
    }

    @Override
    public void attachView(LevelResultView view) {
        super.attachView(view);

        mGetLevelResultSubscriber = new GetLevelResultSubscriber();
        mApiHelper.getLevelResult(mGetLevelResultSubscriber, mLevelRecordId);
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mGetLevelResultSubscriber != null) {
            mGetLevelResultSubscriber.unsubscribe();
            mGetLevelResultSubscriber = null;
        }
        super.detachView(retainInstance);
    }

    private class GetLevelResultSubscriber extends Subscriber<LevelResult> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(mErrMsgServer);
            if (getView() != null) {
                getView().showTimeoutTip();
            }
        }

        @Override
        public void onNext(final LevelResult levelDetail) {
            if (levelDetail.checkState(mContext) && getView() != null) {
                getView().setLevelResult(levelDetail);
            }
        }
    }
}
